<template>  
    <page-container title="简历管理">
        <template #extra>
            <el-input 
                v-model="search" 
                placeholder="请输入关键字" 
                style="width: 120px;height: 30px;margin-left: 50px;" 
                clearable
            />
            <el-button 
                style="margin-left: 30px; background-color: #5defc1; color: white" 
                @click="loadResumeList" 
                plain
            >查询</el-button>
        </template>
        <el-table :data="tableData" style="width: 100%" v-loading="loading">
            <el-table-column prop="name" label="姓名" >
                <template #default="scope">
                     <el-popover effect="light" width="auto" trigger="contextmenu">
                         <template #reference>
                             <el-tag>{{ scope.row.name }}</el-tag>
                         </template>
                     </el-popover>
                 </template>
            </el-table-column>
            <el-table-column prop="email" label="邮箱" width="180"/>
            <el-table-column prop="phone" label="电话" width="160"/>
            <el-table-column prop="intention" label="求职意向" width="150"/>
            <el-table-column prop="summary" label="个人简介" show-overflow-tooltip/>
            <el-table-column prop="education" label="教育经历" show-overflow-tooltip/>
            <el-table-column prop="experience" label="工作经验" show-overflow-tooltip/>
            <el-table-column prop="skills" label="技能特长" show-overflow-tooltip/>
            <el-table-column prop="isApproved" label="简历状态" >
                <template #default="scope">
                     <el-popover effect="light" width="auto" trigger="contextmenu">
                         <template #reference>
                            <el-tag :type="getStatusType(scope.row.isApproved)">
                                        {{ getStatusText(scope.row.isApproved) }}
                                    </el-tag>
                         </template>
                     </el-popover>
                 </template>
            </el-table-column>
            <el-table-column prop="isInvited" label="是否面试">
                <template #default="scope">
                    <el-popover effect="light" width="auto" trigger="contextmenu">
                         <template #reference>
                             <el-tag> {{ scope.row.isInvited===1 ? '是' : '否' }}</el-tag>
                         </template>
                     </el-popover>
                 
                </template>
            </el-table-column>    
            <el-table-column prop="submitTime" label="投递时间" width="180">
                <template #default="{ row }">
                    {{ formatDateTime(row.submitTime) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
                <template #default="scope">
                    <el-tooltip content="查看" placement="top">
                        <el-button 
                            type="primary" 
                            :icon="View"
                            circle
                            size="small"
                            @click="viewResume(scope.row)"
                        />
                    </el-tooltip>
                    <el-tooltip content="下载" placement="top">
                        <el-button 
                            type="success" 
                            :icon="Download"
                            circle
                            size="small"
                            @click="downloadResume(scope.row)"
                        />
                    </el-tooltip>
                    <el-tooltip content="删除" placement="top">
                        <el-button 
                            type="danger" 
                            :icon="Delete"
                            circle
                            size="small"
                            @click="deleteResumes(scope.row)"
                        />
                    </el-tooltip>
                </template>
            </el-table-column>

          <template #empty>
            <el-empty description="暂无数据" />
          </template>
     
        </el-table>
        <template #pagination>
        <div class="demo-pagination-block">
        <el-pagination
            v-show="total > 0"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        />
    </div>
        </template>
        <el-drawer
            v-model="drawerVisible"
            title="简历详情"
            size="60%"
            :destroy-on-close="true"
        >
            <el-descriptions :column="1" border>
                <el-descriptions-item label="姓名">
                    {{ currentResume.name }}
                </el-descriptions-item>
                <el-descriptions-item label="邮箱">
                    {{ currentResume.email }}
                </el-descriptions-item>
                <el-descriptions-item label="电话">
                    {{ currentResume.phone }}
                </el-descriptions-item>
                <el-descriptions-item label="求职意向">
                    {{ currentResume.intention }}
                </el-descriptions-item>
                <el-descriptions-item label="个人简介">
                    {{ currentResume.summary }}
                </el-descriptions-item>
                <el-descriptions-item label="教育经历">
                    {{ currentResume.education }}
                </el-descriptions-item>
                <el-descriptions-item label="工作经验">
                    {{ currentResume.experience }}
                </el-descriptions-item>
                <el-descriptions-item label="技能特长">
                    {{ currentResume.skills }}
                </el-descriptions-item>
            </el-descriptions>

            <el-dialog
                v-model="interviewDialogVisible"
                title="安排面试时间"
                width="30%"
            >
                <el-form
                    ref="interviewFormRef"
                    :model="interviewForm"
                    :rules="interviewRules"
                    label-width="100px"
                >
                    <el-form-item label="面试时间" prop="interviewTime">
                        <el-date-picker
                            v-model="interviewForm.interviewTime"
                            type="datetime"
                            format="YYYY-MM-DD HH:mm:ss"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            placeholder="选择面试时间"
                            :default-time="new Date(2000, 1, 1, 9, 0, 0)"
                            :picker-options="{
                                disabledDate(time) {
                                    return time.getTime() < Date.now() - 8.64e7
                                },
                                selectableRange: ['09:00:00 - 18:00:00']
                            }"
                        />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="interviewDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="confirmInterview">确定</el-button>
                    </span>
                </template>
            </el-dialog>

            <template #footer>
                <div style="flex: auto">
                    <el-button @click="drawerVisible = false">关闭</el-button>
                    <el-button 
                        type="success" 
                        @click="handleInvite"
                        :loading="inviteLoading"
                    >邀请面试</el-button>
                    <el-button 
                        type="danger" 
                        @click="handleReject"
                        :loading="rejectLoading"
                    >驳回申请</el-button>
                </div>
            </template>
        </el-drawer>
    </page-container>
</template>

<script setup>
import PageContainer from '@/components/PageContainer.vue'
import { ref, onMounted } from 'vue'
import { getResumeList, inviteInterview, rejectResume,deleteResume,exportPdf } from '@/api/resume'
import { addInterview } from '@/api/interview'
import { ElMessage, ElMessageBox } from 'element-plus'
import { View, Download, Delete } from '@element-plus/icons-vue'
import eventBus from '@/utils/eventBus'

const tableData = ref([])
const loading = ref(true)
const drawerVisible = ref(false)
const currentResume = ref({})
const inviteLoading = ref(false)
const rejectLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const search = ref('')
const total = ref(0)
const interviewDialogVisible = ref(false)
const interviewFormRef = ref(null)
const interviewForm = ref({
    interviewTime: ''
})
const admin=JSON.parse(localStorage.getItem("admin"))
const interviewRules = {
    interviewTime: [
        { required: true, message: '请选择面试时间', trigger: 'change' },
        {
            validator: (rule, value, callback) => {
                if (!value) {
                    callback()
                    return
                }
                const time = new Date(value)
                const hours = time.getHours()
                if (hours < 9 || hours >= 18) {
                    callback(new Error('请选择工作时间 (9:00-18:00)'))
                } else {
                    callback()
                }
            },
            trigger: 'change'
        }
    ]
}

const loadResumeList = async () => {
    loading.value = true
    try{
        const res = await getResumeList({
            current: currentPage.value,
            size: pageSize.value,
            search: search.value
        })
        
        if(res.code===200){
            tableData.value = res.data.records
            total.value = res.data.total
        }
    }catch(error){
        ElMessage.error('获取简历列表失败')
    }finally{
        loading.value = false
    }
}
const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
    loadPositions()
}
const handleCurrentChange = (val) => {
    currentPage.value = val
    loadPositions()
}
const viewResume = (row) => {
    currentResume.value = { ...row }
    drawerVisible.value = true
}
const deleteResumes= async (row)=>{
  if(schema()) {
    try {
      await ElMessageBox.confirm(
          `确定要删除 ${row.name} 的简历吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      )
      const res = await deleteResume(row.id)
      if (res.code === 200) {
        ElMessage.success('删除简历成功')
        loadResumeList()
      } else {
        ElMessage.error(res.message)
      }
    } catch (error) {
      ElMessage.error('删除简历失败')
    }
  }
}
//下载简历
const downloadResume = async (row) => {
    try {
        const res = await exportPdf(row.userId)
        console.log(res)
        // 创建 blob 对象，指定正确的 MIME 类型
        const blob = new Blob([res], { type: 'application/pdf' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', `${row.name}_`+`${row.intention}_简历.pdf`)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)  // 释放 URL 对象
        
        ElMessage.success('导出成功')
    } catch (error) {
        console.error('导出失败：', error)
        ElMessage.error('导出失败：' + error.message)
    }
}
const handleInvite = async () => {
    interviewForm.value.interviewTime = ''
    interviewDialogVisible.value = true
}

const handleError = (error) => {
    console.error('操作失败：', error)
    if (error.response) {
        console.error('响应数据：', error.response.data)
        ElMessage.error(error.response.data.message || '操作失败')
    } else {
        ElMessage.error(error.message || '操作失败')
    }
}

const confirmInterview = async () => {
  if(schema()) {
    if (!interviewFormRef.value) return

    await interviewFormRef.value.validate(async (valid) => {
      if (valid) {
        try {
          inviteLoading.value = true
          const res = await inviteInterview(currentResume.value.id)

          if (res.code === 200) {
            const interviewData = {
              userId: currentResume.value.userId,
              candidateName: currentResume.value.name,
              positionName: currentResume.value.intention,
              name: JSON.parse(localStorage.getItem('admin')).username,
              interviewTime: interviewForm.value.interviewTime,
              status: 0
            }

            console.log('发送的面试数据：', interviewData)
            try {
              const addRes = await addInterview(interviewData)
              if (addRes.code === 200) {
                ElMessage.success('已发送面试邀请')
                interviewDialogVisible.value = false
                drawerVisible.value = false
                loadResumeList()
                eventBus.emit('updatePendingCount')
              } else {
                throw new Error(addRes.message || '添加面试记录失败')
              }
            } catch (error) {
              await rejectResume(currentResume.value.id)
              throw error
            }
          } else {
            ElMessage.error(res.message || '操作失败')
          }
        } catch (error) {
          handleError(error)
        } finally {
          inviteLoading.value = false
        }
      }
    })
  }
}

const handleReject = async () => {
  if(schema()){
    try {
      await ElMessageBox.confirm(
          `确定要驳回 ${currentResume.value.name} 的申请吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      )

      rejectLoading.value = true
      const res = await rejectResume(currentResume.value.id)

      if (res.code === 200) {
        ElMessage.success('已驳回申请')
        drawerVisible.value = false
        await loadResumeList()  // 刷新列表
        eventBus.emit('updatePendingCount')
      } else {
        ElMessage.error(res.message || '操作失败')
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('驳回失败：', error)
        ElMessage.error('驳回失败：' + error.message)
      }
    } finally {
      rejectLoading.value = false
    }
  }

}
const formatDateTime = (dateStr) => {
    if (!dateStr) return '--'
    const date = new Date(dateStr)
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    })
}

const getStatusType = (status) => {
    const statusMap = {
        0: 'info',  
        1: 'success',
        2: 'danger'
        
    }
    return statusMap[status] || 'info'
}

const getStatusText = (status) => {
    const statusMap = {
        0: '待审核',
        1: '已通过',
        2: '未通过'
    }
    return statusMap[status] || status
}

const schema = () => {
  if (admin === null) {
    ElMessage.warning('您没有权限进行此操作');
    return false;
  }
  // 其他权限检查逻辑
  if (admin.role === 'super_admin' || admin.role === 'admin') {
    console.log(admin.role);
    return true;
  } else {
    ElMessage.warning('您没有权限进行此操作');
    return false;
  }
}
onMounted(() => {
    setTimeout(() => {
        loadResumeList()
    }, 1000)
})
</script>

<style scoped>
:deep(.el-descriptions__label) {
    width: 120px;
    font-weight: bold;
}

:deep(.el-descriptions__content) {
    white-space: pre-line;  /* 保留换行符 */
}
.demo-pagination-block {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}
</style>